package com.typing.interceptor;

import com.typing.entity.AdminEntity;
import com.typing.service.AdminService;
import com.typing.utils.AccountException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class AdminInterceptor implements HandlerInterceptor {

	private static final String TAG = "tag";

	private static final String DEV = "dev";

	@Resource
	AdminService adminService;

	@Value("${config.state}")
	private String state;


	/**
	 * 拦截没有登录或者多个设备登录
	 *
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// TODO: 2022/11/30 目前拦截器已开启，如需关闭更改config.properties文件（config.state=dev）
		if (!DEV.equals(state)) {
			//	设置响应头
			response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
			response.setHeader("Access-Control-Allow-Credentials", "true");
			response.setHeader("P3P", "CP=CAO PSA OUR");
			if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
				response.addHeader("Access-Control-Allow-Methods", "POST,GET,TRACE,OPTIONS");
				response.addHeader("Access-Control-Allow-Headers", "Content-Type,Origin,Accept,tag");
				response.addHeader("Access-Control-Max-Age", "120");
			}
			if(!(handler instanceof HandlerMethod)){
				return false;
			}
			response.setContentType("application/json;charset=utf-8");
			//	禁止走缓存
			response.setHeader("Pragma", "no-cache");
			String tag = request.getHeader(TAG);
			if ("".equals(tag) || tag == null) {
				throw new AccountException();
			}
			//	通过tag值进行查询
			AdminEntity admins = adminService.selectTag(tag);
			//	如果查询出来是空的则拦截，返回状态
			if (admins == null) {
				throw new AccountException();
			}
		}
		return true;
	}
}
